using System;
using System.IO;
using System.Threading.Tasks;
using HandyControl.Controls;
using Common.Untils;
using SanmaoTools.Services;
using System.Text.Json;

namespace Tryit.Services
{
    public class DatabaseBackupService
    {
        private readonly string _backupDirectory;
        private readonly string _dbPath;
        private readonly LogService _logService;
        private readonly string _backupInfoPath;
        private DateTime? _lastBackupDate;

        public DatabaseBackupService()
        {
            _backupDirectory = Path.Combine(
                Environment.CurrentDirectory,
                "Backups"
            );
            _dbPath = Path.Combine(Environment.CurrentDirectory, "DataBase", "Data.db");
            _logService = new LogService();
            _backupInfoPath = Path.Combine(_backupDirectory, "backup_info.json");
            LoadLastBackupDate();
        }

        private void LoadLastBackupDate()
        {
            try
            {
                if (File.Exists(_backupInfoPath))
                {
                    var json = File.ReadAllText(_backupInfoPath);
                    var info = JsonSerializer.Deserialize<BackupInfo>(json);
                    _lastBackupDate = info.LastBackupDate;
                }
            }
            catch (Exception ex)
            {
                _logService.LogError($"加载备份信息失败: {ex.Message}");
            }
        }

        private void SaveLastBackupDate()
        {
            try
            {
                var info = new BackupInfo { LastBackupDate = DateTime.Now };
                var json = JsonSerializer.Serialize(info);
                File.WriteAllText(_backupInfoPath, json);
                _lastBackupDate = DateTime.Now;
            }
            catch (Exception ex)
            {
                _logService.LogError($"保存备份信息失败: {ex.Message}");
            }
        }

        public async Task<bool> BackupDatabaseAsync()
        {
            try
            {
                if (!File.Exists(_dbPath))
                {
                    _logService.LogError($"数据库文件不存在: {_dbPath}");
                    return false;
                }

                // 检查今天是否已经备份过
                if (_lastBackupDate.HasValue && _lastBackupDate.Value.Date == DateTime.Now.Date)
                {
                    _logService.LogInformation("今天已经进行过自动备份，跳过本次备份");
                    return false;
                }

                // 确保备份目录存在
                Directory.CreateDirectory(_backupDirectory);

                // 生成备份文件名（使用时间戳）
                string timestamp = DateTime.Now.ToString("yyyyMMdd_HHmmss");
                string backupFileName = $"Data_Backup_{timestamp}.db";
                string backupPath = Path.Combine(_backupDirectory, backupFileName);

                // 复制数据库文件
                File.Copy(_dbPath, backupPath, true);

                // 清理旧备份（保留最近一年的备份）
                CleanupOldBackups();

                // 更新最后备份日期
                SaveLastBackupDate();

                _logService.LogInformation($"数据库备份成功: {backupPath}");
                return true;
            }
            catch (Exception ex)
            {
                _logService.LogError($"数据库备份失败: {ex.Message}");
                return false;
            }
        }

        public async Task<bool> ManualBackupAsync()
        {
            try
            {
                if (!File.Exists(_dbPath))
                {
                    MessageBox.Error("数据库文件不存在", "备份失败");
                    return false;
                }

                // 确保备份目录存在
                Directory.CreateDirectory(_backupDirectory);

                // 生成备份文件名（使用时间戳）
                string timestamp = DateTime.Now.ToString("yyyyMMdd_HHmmss");
                string backupFileName = $"Data_Backup_Manual_{timestamp}.db";
                string backupPath = Path.Combine(_backupDirectory, backupFileName);

                // 复制数据库文件
                File.Copy(_dbPath, backupPath, true);

                _logService.LogInformation($"手动备份成功: {backupPath}");
                MessageBox.Success($"备份成功\n保存位置：{backupPath}", "备份完成");
                return true;
            }
            catch (Exception ex)
            {
                _logService.LogError($"手动备份失败: {ex.Message}");
                MessageBox.Error($"备份失败：{ex.Message}", "错误");
                return false;
            }
        }

        private void CleanupOldBackups()
        {
            try
            {
                var backupFiles = Directory.GetFiles(_backupDirectory, "Data_Backup_*.db");
                var cutoffDate = DateTime.Now.AddYears(-1);

                foreach (var file in backupFiles)
                {
                    var fileInfo = new FileInfo(file);
                    if (fileInfo.CreationTime < cutoffDate)
                    {
                        fileInfo.Delete();
                        _logService.LogInformation($"已删除旧备份文件: {file}");
                    }
                }
            }
            catch (Exception ex)
            {
                _logService.LogError($"清理旧备份失败: {ex.Message}");
            }
        }

        public bool ShouldBackupToday(int backupDay)
        {
            var today = DateTime.Now.Day;
            return today == backupDay;
        }
    }

    public class BackupInfo
    {
        public DateTime LastBackupDate { get; set; }
    }
} 